package com.bootdo.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.*;
import com.bootdo.common.utils.excel.MemberMoneyExcelUtils;
import com.bootdo.wx.dao.*;
import com.bootdo.wx.domain.CmsSlideDO;
import com.bootdo.wx.domain.MemberLevelChangeDO;
import com.bootdo.wx.service.*;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.bootdo.wx.domain.MemberUserDO;
import org.jsoup.Connection.Response;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;


@Service
public class MemberUserServiceImpl implements MemberUserService {
	@Autowired
	private MemberUserDao memberUserDao;
	@Autowired
	private OrderComService orderComService;
	@Autowired
	private MemberCouponDao memberCouponDao;
	@Autowired
	private OrderOrderDao orderOrderDao;
	@Autowired
	public CmsSlideDao cmsSlideDao;
	@Autowired
	public MemberTokenService memberTokenService;
	@Autowired
	public SetImageUploadService setImageUploadService;
	@Autowired
	private CmsContentDao cmsContentDao;
	@Autowired
	private MemberScoreDao memberScoreDao;
	@Autowired
	private MemberSignService memberSignService;
	@Autowired
	private MemberLevelChangeDao memberLevelChangeDao;
	@Autowired
	private OrderComDao orderComDao;
	
	@Override
	public MemberUserDO get(String id){
		return memberUserDao.get(id);
	}
	
	@Override
	public List<MemberUserDO> list(Map<String, Object> map){
		return memberUserDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return memberUserDao.count(map);
	}
	
	@Override
	public int save(MemberUserDO memberUser){
		return memberUserDao.save(memberUser);
	}
	
	@Override
	public int update(MemberUserDO memberUser){
		return memberUserDao.update(memberUser);
	}
	
	@Override
	public int remove(String id){
		return memberUserDao.remove(id);
	}
	
	@Override
	public int batchRemove(String[] ids){
		return memberUserDao.batchRemove(ids);
	}

	/*个人详细信息*/
	@Override
	public Map<String,Object> getMemberCenter(Map<String, Object> params) {
		String userId = params.get("userId").toString();
		MemberUserDO memberUserDO = memberUserDao.get(userId);
		Map<String,Object> map = new HashMap<String,Object>();
		//用信息
		/*map.put("phone",memberUserDO.getPhone());
		map.put("wechat",memberUserDO.getWechat());*/
		map.put("name",memberUserDO.getName());
		map.put("avator",memberUserDO.getAvator());
		map.put("level",memberUserDO.getLevel());
		map.put("sex",memberUserDO.getSex());
		map.put("postType", memberUserDO.getPostType());   //配送方式
		String introUser = memberUserDO.getIntroUser();
		MemberUserDO introUserDO = memberUserDao.get(introUser);
		if (introUserDO == null) {
			map.put("fatherAvator","");
			map.put("fatherName","");
		} else {
			map.put("fatherAvator",introUserDO.getAvator());
			map.put("fatherName",introUserDO.getName());
		}
		//积分
		BigDecimal scoreNumber = memberScoreDao.getSumByUser(params);
		map.put("scoreNum", scoreNumber);   //积分
		//签到状态  0：未签到，1：签到
		/*if (memberSignService.getTodaySign(userId).size() != 0) {
			map.put("isCheck", "1");
		} else {
			map.put("isCheck", "0");
		}*/
		//商家地址
		/*String address = cmsContentDao.getByType("shop-address").getValue();
		map.put("shopAddress", address);*/   //地址
		//余额
		Map<String,Object> moneyMap = orderComService.getMemberCom(params);
		map.put("sPrice", moneyMap.get("sPrice"));   //收益
		map.put("allPrice", moneyMap.get("allPrice"));   //余额
		map.put("canExPrice", moneyMap.get("canExPrice"));   //可提现余额
		params.remove("type");
		//优惠券数量
		/*List<String> types = new ArrayList<String>();
		types.add("0");
		params.put("types", types);
		int couponNum = memberCouponDao.getMyCouponList(params).size();
		map.put("couponNum", couponNum);   //优惠券总数*/
		//订单个数
		params.remove("types");
		String [] status = new String[10];
		status[0] = "1";
		params.put("status", status);
		int payNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "3";
		int faNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "2";
		int ptNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "4";
		int shouNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "11";
		int tiNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "7";
		params.put("type", "4");
		int wcNum = orderOrderDao.getOrderListByStatus(params).size();
		status[0] = "5";
		status[1] = "6";
		status[2] = "8";
		int errorNum = orderOrderDao.getOrderListByStatus(params).size();
		map.put("payNum", payNum);   //待支付
		map.put("faNum", faNum);   //待发货
		map.put("shouNum", shouNum);   //待收货
		map.put("tiNum", tiNum);   //自提
		map.put("errorNum", errorNum);   //错误订单
		map.put("wcNum", wcNum);   //已完成(评价)订单
		map.put("ptNum", ptNum);   //拼团订单
		//我的粉丝
		params.remove("status");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		int allNum = memberUserDao.getFansNum(params);   //总共粉丝数
		/*params.put("staTime", format.format(DateUtils.getDayBegin()));
		int todayNum = memberUserDao.getFansNum(params);   //今天粉丝数
		params.put("endTime", format.format(DateUtils.getDayBegin()));
		params.put("staTime", format.format(DateUtils.getBeginDayOfYesterday()));
		int yesterdayNum = memberUserDao.getFansNum(params);   //昨天粉丝数*/
		map.put("allNum",allNum);
		/*map.put("todayNum",todayNum);
		map.put("yesterdayNum",yesterdayNum);*/
		//冻结金额
		map.put("freezeMoney", orderComDao.getMemberFreezeMoney(userId));
		return map;
	}

	@Override
	public PageInfo<Map<String,Object>> getMyFans(Map<String, Object> paramMap) {
		PageHelperUtils.page(paramMap);
		List<Map<String,Object>> list =memberUserDao.getMyFans(paramMap);
		PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	@Override
	public MemberUserDO queryByOpenid(String openId) {
		return memberUserDao.queryByOpenid(openId);
	}

	@Override
	public List<Map<String,Object>> getOrderEcharts(Map<String,Object> map) {
		return memberUserDao.getOrderEcharts(map);
	}

	@Override
	public List<Map<String,Object>> allMoneyEcharts(Map<String,Object> map) {
		return memberUserDao.allMoneyEcharts(map);
	}

	@Override
	public List<Map<String,Object>> allUserEcharts(Map<String,Object> map) {
		return memberUserDao.allUserEcharts(map);
	}

	@Override
	public MemberUserDO getByCode(String code) {
		return memberUserDao.getByCode(code);
	}

	@Override
	public R getExtension(Map<String, Object> params) {
		String userId = params.get("userId").toString();
		Map<String,Object> map = new HashMap<String,Object>();
		MemberUserDO userDO = memberUserDao.get(userId);
		map.put("avator",userDO.getAvator());
		map.put("name", userDO.getName());
		map.put("InvitationCode",userDO.getCode());
		String code = userDO.getCode();
		params.clear();
		params.put("type", "3");
		List<CmsSlideDO> imgList = cmsSlideDao.queryAll(params);
		if (imgList.size() == 0) {
			map.put("imgurl","");
		} else {
			map.put("imgurl",imgList.get(0).getImgUrl());
		}
		if (userDO.getQrcode() != null && !"".equals(userDO.getQrcode())) {
			map.put("qrCode",userDO.getQrcode());
		} else {   //如果库里面没有生成二维码，就生成
			String token = memberTokenService.getToken();
			String url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+token;
			Map<String,String> urlMap = new HashMap<String,String>();
			//urlMap.put("access_token",token); 不能传，会报错，微信文档错了
			urlMap.put("scene",code);
			//urlMap.put("page","");     //制定跳小程序的页面，不过不指定，默认跳首页
			try {
				Gson gson = new Gson();
				Response response = HttpUtils.post(url, gson.toJson(urlMap));
				String contentType = response.contentType();
				if (!"image/jpeg".equals(contentType)) {   //没返回图片
					String body = response.body();
					Map<String, Object> resultMap = new HashMap<String, Object>();
					resultMap = gson.fromJson(body, resultMap.getClass());
					System.out.print("获取二维码结果：：" + resultMap.toString());
					return R.error("获取二维码code值："+resultMap.get("errcode").toString());
				}
				//图片上传
				InputStream is = response.bodyStream();
				byte [] imgByte = StringUtils.readInputStream(is);
				BufferedImage image = ImageIO.read(is);
				String fileName = null;
				if (image != null) {//如果image=null 表示上传的不是图片格式
					fileName = "IMG_" + image.getWidth() + "_" + image.getHeight() + "@"+ UUID.randomUUID().toString();;
				}else {
					fileName = UUID.randomUUID().toString();
				}
				String imagePath = new ImgUpload(setImageUploadService).upload(imgByte,
						fileName);
				System.out.println("生成二维码地址地址：："+imagePath);
				MemberUserDO memberUserDO = new MemberUserDO();
				memberUserDO.setId(userId);
				memberUserDO.setQrcode(imagePath);
				memberUserDao.update(memberUserDO);
				map.put("qrCode",imagePath);
			} catch (Exception e) {
				e.printStackTrace();
				return R.error("生成二维码失败");
			}
		}
		return R.ok().put("data",map);
	}

	@Override
	public List<Map<String,Object>> getMoneyListByUser(Map<String,Object> map) {
		return memberUserDao.getMoneyListByUser(map);
	}

	@Override
	public int getMoneyListByUserCount(Map<String, Object> map) {
		return memberUserDao.getMoneyListByUserCount(map);
	}

	/*导出excel。改变订单导出状态*/
	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void exportExcel(Map<String,Object> map,List<Map<String,Object>> userList,
							ServletOutputStream out,HttpServletRequest request) {
		//导出excel
		MemberMoneyExcelUtils.exportUserExcel(userList, out);
	}

	@Override
	public List<Map<String,Object>> getMyFansH(Map<String,Object> map) {
		return memberUserDao.getMyFansH(map);
	}

	@Override
	public int getMyFansHCount(Map<String, Object> map) {
		return memberUserDao.getMyFansHCount(map);
	}

	@Override
	public BigDecimal getShoppingNum(Map<String,Object> map) {
		return memberUserDao.getShoppingNum(map);
	}

	@Override
	public List<Map<String,Object>> getShoppingList(Map<String,Object> map) {
		return memberUserDao.getShoppingList(map);
	}

	@Override
	public int getShoppingListCount(Map<String, Object> map) {
		return memberUserDao.getShoppingListCount(map);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public void shoppingExportExcel(Map<String,Object> map,List<Map<String,Object>> shoppingList,
							ServletOutputStream out,HttpServletRequest request) {
		//导出excel
		MemberMoneyExcelUtils.exportPTShoppingExcel(shoppingList, out);
	}

	@Override
	public int getZtChildrenNUm(Map<String, Object> map) {
		return memberUserDao.getZtChildrenNUm(map);
	}

	@Override
	@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED) // 有事务则加入,没有则建立
	public R updateLevel(MemberUserDO userDO) {
		String userId = userDO.getId();
		MemberUserDO oldUser = memberUserDao.get(userId);
		memberUserDao.update(userDO);
		//添加等级变动记录
		MemberLevelChangeDO changeDO = new MemberLevelChangeDO();
		changeDO.setId(UuidUtil.get32UUID());
		changeDO.setOldLevel(oldUser.getLevel());
		changeDO.setNewLevel(userDO.getLevel());
		changeDO.setCreateAt(new Date());
		changeDO.setUpdateAt(new Date());
		changeDO.setDelFlag(0);
		changeDO.setComent("后台修改");
		memberLevelChangeDao.save(changeDO);
		return R.ok();
	}

	@Override
	public MemberUserDO findByPhone(String phoneNumber) {
		
		return memberUserDao.findByPhone(phoneNumber);
	}

	@Override
	public R setMemberDays(Map<String, Object> map) {
		MemberUserDO memberUserDO = memberUserDao.get(map.get("userId").toString());
		Date stringToDate = DateUtils.getStringToDate(map.get("days").toString());
		if(stringToDate.after(new Date())){
			return R.error("设置的停经的天数不能大于当前日期");
		}
		memberUserDO.setBabyDays(map.get("days").toString());
		memberUserDao.update(memberUserDO);
		//计算预产期
		try {
			Date date = DateUtils.getStringToDate(map.get("days").toString());
			int parseInt = Integer.parseInt(cmsContentDao.getByType("baoma_yunqi_days").getValue())*7;
			Date addDayOfDate = DateUtils.addDayOfDate(date,parseInt);
			return R.ok().put("data", DateUtils.format(addDayOfDate, DateUtils.DATE_PATTERN));
		} catch (Exception e) {
			e.printStackTrace();
			return R.error();
		}
		
	}

	@Override
	public R getOverdue(Map<String, Object> map) {
		if(map.get("userId")==null||"".equals(map.get("userId").toString())){
			return R.ok().put("data", "请登录");
		}
		MemberUserDO memberUserDO = memberUserDao.get(map.get("userId").toString());
		if(memberUserDO==null ){
			return R.error("用户信息有误");
		}else if(memberUserDO.getBabyDays()==null||"".equals(memberUserDO.getBabyDays())){
			return R.ok().put("data", null);
		}else{
			try {
				Date date = DateUtils.getStringToDate(memberUserDO.getBabyDays());
				int parseInt = Integer.parseInt(cmsContentDao.getByType("baoma_yunqi_days").getValue())*7;
				Date addDayOfDate = DateUtils.addDayOfDate(date,parseInt);
				return R.ok().put("data", DateUtils.format(addDayOfDate, DateUtils.DATE_PATTERN));
			} catch (Exception e) {
				e.printStackTrace();
				return R.error();
			}
		}
	}

	@Override
	public List<Map<String, Object>> getMyXJFans(Map<String, Object> map) {
		return memberUserDao.getMyFans(map);
	}



}
